package com.joysuch.wwyt.bp.service.impl;

import com.joysuch.wwyt.bp.bean.inspect.BPInspectItemTypeBean;
import com.joysuch.wwyt.bp.entity.inspect.BPInspectItemType;
import com.joysuch.wwyt.bp.repository.BPInspectItemTypeDao;
import com.joysuch.wwyt.bp.service.BPInspectItemTypeService;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

/**
 * 巡检： 检查项类型Service
 */

@Slf4j
@Service
@Transactional
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class BPInspectItemTypeServiceImpl implements BPInspectItemTypeService {

    @Autowired
    private BPInspectItemTypeDao inspectItemTypeDao;

    @Override
    public List<BPInspectItemType> findList(){
        return inspectItemTypeDao.findAll();
    }

    @Override
    public ResultBean save(BPInspectItemTypeBean bean){
        BPInspectItemType dbEntity = inspectItemTypeDao.findByItemType(bean.getItemType());
        BPInspectItemType entity = null;
        if(bean.getId() == null || bean.getId()== 0){
            if(dbEntity != null){
                return ResultBean.wrapErrorResultDefault("检查点项目分类已经存在。");
            }
            entity = new BPInspectItemType();
        }else{
            if(dbEntity != null && !dbEntity.getId().equals(bean.getId())){
                return ResultBean.wrapErrorResultDefault("检查点项目分类不能重复");
            }
            entity = inspectItemTypeDao.findById(bean.getId()).get();
        }
         entity.setItemType(bean.getItemType());

        return  ResultBean.success(inspectItemTypeDao.save(entity));
    }

    @Override
    public void deleteById(Long id){
        inspectItemTypeDao.deleteById(id);
    }

    @Override
    public BPInspectItemType getById(Long id) {
       Optional<BPInspectItemType> optional =   inspectItemTypeDao.findById(id);
        return optional.isPresent() ? optional.get() : null;
    }

}
